package com.kzhkwkt.sugoieditor;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.Toast;

public class SugoiEditor extends Activity implements OnKeyListener {
	private static final String TAG = "SugoiEditor";

	private EditText editContents = null;

	Data data = null;
	ActiveFile activeFile = null;
	SoundPlayer player = null;
	PreferenceAdmin prefAdmin = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate in");
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.main);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);

		if(savedInstanceState != null) {
			Log.i(TAG, savedInstanceState.toString());
		}

        data = Data.getInstance(this);
        player = new SoundPlayer(this);
        prefAdmin = new PreferenceAdmin(this);

        editContents = (EditText)findViewById(R.id.editor);
        editContents.setOnKeyListener(this);
		Log.i(TAG, "onCreate out");
    }

    @Override
    public void onStart() {
		Log.i(TAG, "onStart in");
    	super.onStart();
    	SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
    	prefAdmin.setColor(editContents, pref.getBoolean("color_set_key", false));
    	prefAdmin.setOrientation(pref.getBoolean("landscape_allowed_key", false));
		Log.i(TAG, "onStart out");
    }

    /**
     * キーが押された時の挙動
     */
    public boolean onKey(View view, int i, KeyEvent keyevent) {
		if(keyevent.getAction() == KeyEvent.ACTION_DOWN) {
			//player.start(R.raw.keydown);
			Log.i("KEY DOWN", "" + keyevent.getKeyCode());
		}
		return false;
	}

    /**
     * ファイルを保存する
     * @return 保存に成功 : true / それ以外はfalse
     */
    boolean save() {
		Log.i(TAG, "save in");
		if(activeFile == null) {
			Intent intent = new Intent(this, TitleEdit.class);
			startActivityForResult(intent, C.RequestCode.EDIT_TITLE);
			return false;
		}
		activeFile.setContents(editContents.getText().toString());
		Log.i(TAG, "save out");
		if(data.save(activeFile)) {
			showSuccess(getString(R.string.success_save));
			return true;
		}
		else {
			return false;
		}
    }

    /**
     * ファイルを開く
     * @return ファイルを開けたらtrue / ファイルが１個もなかったらfalse
     */
    boolean load() {
		Log.i(TAG, "load in");
		if(data.count() <= 0) {
			showError(getString(R.string.error_no_file));
			return false;
		}
		Intent intent = new Intent(this, FileList.class);
		startActivityForResult(intent, C.RequestCode.OPEN);

		Log.i(TAG, "load out");
		return true;
	}

    /**
     * テキストがロード時から変更されているかを判定する
     * @return 変更されていなければtrue / されていればfalse
     */
    boolean compare() {
    	if(isFileLoaded()) {
    		return editContents.getText().toString().equals(activeFile.getContents());
    	}
    	return true;
    }

	/**
     * 新規ファイルを作成する
     * @return 今のとこ常にtrue
     */
	boolean createNewFile() {
		Log.i(TAG, "newFile in");
		if(!compare()) {

		}
		setTitle(getString(R.string.default_new_file_title) + getString(R.string.app_name));
		editContents.setText("");
		activeFile = null;
		Log.i(TAG, "newFile out");
		return true;
	}

	/**
	 * 外部SDカードへファイルを保存する
	 * @return 成功したらtrue / それ以外はfalse
	 */
	boolean export() {
		Exporter ex = new Exporter();
		return ex.execute(activeFile);
	}

    void showError(String message) {
    	Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    void showSuccess(String message) {
    	Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    /**
     * ファイルがなんかしら開かれているかを判定する
     * @return 開かれていればtrue / それ以外はfalse
     */
    boolean isFileLoaded() {
    	return (activeFile != null);
    }

    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		Log.i(TAG, "onActivityResult in");
		if(requestCode == C.RequestCode.OPEN && resultCode == C.ResponseCode.OPEN) {
			activeFile = (ActiveFile)intent.getSerializableExtra(FileList.ACTIVE_FILE);
			if(activeFile.getId() == 0) {
				return;
			}
			setTitle(activeFile.getTitle());
			editContents.setText(activeFile.getContents());
		}

		if(requestCode == C.RequestCode.EDIT_TITLE) {
			if(resultCode == C.ResponseCode.EDIT_TITLE) {
				if(!isFileLoaded()) activeFile = new ActiveFile();

				String title = intent.getStringExtra(TitleEdit.TITLE_KEY);
				activeFile.setTitle(title);
				save();
			}
		}
		Log.i(TAG, "onActivityResult out");
	}

    // --------------------------------------------------------------------------------------------
    // Menu 操作
    // --------------------------------------------------------------------------------------------

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.i(TAG, "onCreateOptionsMenu in");
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		Log.i(TAG, "onCreateOptionsMenu out");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		Log.i(TAG, "onPreapareOptionsMenu in");
		if(!isFileLoaded()) {
			menu.findItem(R.id.menuitem_delete).setEnabled(false);
			if(editContents.getText().length() == 0) {
				menu.findItem(R.id.menuitem_save).setEnabled(false);
			}
			else {
				menu.findItem(R.id.menuitem_save).setEnabled(true);
			}
		}
		else {
			menu.findItem(R.id.menuitem_delete).setEnabled(true);
			menu.findItem(R.id.menuitem_save).setEnabled(true);
		}
		Log.i(TAG, "onPreapareOptionsMenu out");
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i(TAG, "onOptionsItemSelected in");
    	Log.i(TAG, "Selected item = " + item.getTitle());
    	switch(item.getItemId()) {
    	case R.id.menuitem_save:
    		return save();
    	case R.id.menuitem_load:
    		return load();
    	case R.id.menuitem_new:
    		return createNewFile();
    	case R.id.menuitem_pref:
    		startActivity(new Intent(this, Preference.class));
    	case R.id.menuitem_delete:
    		break;
    	case R.id.menuitem_export:
    		return export();
    	default:
    		break;
    	}

		Log.i(TAG, "onOptionsItemSelected out");
    	return super.onOptionsItemSelected(item);
    }
}